#!/usr/bin/env node

// {{ AURA-X: Create - 生成Chrome插件图标的Node.js脚本. Approval: 寸止 }}

const fs = require('fs');
const path = require('path');

// 检查canvas库是否安装
let Canvas;
try {
  Canvas = require('canvas');
} catch (err) {
  console.error('❌ canvas库未安装');
  console.log('\n请运行以下命令安装依赖：');
  console.log('  npm install canvas\n');
  process.exit(1);
}

const { createCanvas } = Canvas;

/**
 * 绘制图标
 * @param {number} size - 图标尺寸
 */
function drawIcon(size) {
  const canvas = createCanvas(size, size);
  const ctx = canvas.getContext('2d');
  
  // 创建渐变背景
  const gradient = ctx.createLinearGradient(0, 0, size, size);
  gradient.addColorStop(0, '#667eea');
  gradient.addColorStop(1, '#764ba2');
  
  // 绘制圆角矩形背景
  const radius = size * 0.2;
  ctx.fillStyle = gradient;
  ctx.beginPath();
  ctx.moveTo(radius, 0);
  ctx.lineTo(size - radius, 0);
  ctx.quadraticCurveTo(size, 0, size, radius);
  ctx.lineTo(size, size - radius);
  ctx.quadraticCurveTo(size, size, size - radius, size);
  ctx.lineTo(radius, size);
  ctx.quadraticCurveTo(0, size, 0, size - radius);
  ctx.lineTo(0, radius);
  ctx.quadraticCurveTo(0, 0, radius, 0);
  ctx.closePath();
  ctx.fill();
  
  // 绘制字母 "A"
  ctx.fillStyle = 'white';
  ctx.font = `bold ${size * 0.6}px Arial`;
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText('A', size / 2, size / 2);
  
  return canvas;
}

/**
 * 保存图标
 * @param {Canvas} canvas - canvas对象
 * @param {string} filename - 文件名
 */
function saveIcon(canvas, filename) {
  const buffer = canvas.toBuffer('image/png');
  const filePath = path.join(__dirname, 'icons', filename);
  
  fs.writeFileSync(filePath, buffer);
  console.log(`✅ 已生成: ${filename}`);
}

/**
 * 主函数
 */
function main() {
  console.log('🎨 开始生成Chrome插件图标...\n');
  
  // 确保icons目录存在
  const iconsDir = path.join(__dirname, 'icons');
  if (!fs.existsSync(iconsDir)) {
    fs.mkdirSync(iconsDir);
    console.log('📁 创建icons目录\n');
  }
  
  // 生成不同尺寸的图标
  const sizes = [
    { size: 16, filename: 'icon16.png' },
    { size: 48, filename: 'icon48.png' },
    { size: 128, filename: 'icon128.png' }
  ];
  
  sizes.forEach(({ size, filename }) => {
    const canvas = drawIcon(size);
    saveIcon(canvas, filename);
  });
  
  console.log('\n✨ 所有图标生成完成！');
  console.log('\n位置: icons/');
  console.log('  - icon16.png');
  console.log('  - icon48.png');
  console.log('  - icon128.png');
  console.log('\n现在可以在 chrome://extensions/ 加载插件了！');
}

// 运行
main();

